package org.nebuloop.photo.organizer;

import java.io.File;
import java.io.IOException;
import java.util.Properties;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.atomic.AtomicLong;
import java.util.logging.Level;
import java.util.logging.Logger;

import org.nebuloop.photo.organizer.dao.ImageDAO;

public class ImageProcessingRunner implements Runnable {

  private static final Logger LOGGER = Logger.getLogger(ImageProcessingRunner.class.getCanonicalName());
  private final ImageProcessor imageProcessor = new ImageProcessor();
  private final AtomicLong processedImagesCount = new AtomicLong(0);
  private String destinationDirectory;
  final Properties sourceProperties = new Properties();
  private boolean isInterrupted;
  private final BlockingQueue<File> queue;

  public ImageProcessingRunner(BlockingQueue<File> queue) {
    this.queue = queue;
  }

  public void init(ImageDAO imageDao, boolean preserveNonNumericFolderName, String skippedFilesDestinationDirectory)
      throws Exception {
    imageProcessor.setDestinationDirectory(destinationDirectory);
    imageProcessor.setImageDao(imageDao);
    imageProcessor.setPreserveNonNumericFolderName(preserveNonNumericFolderName);
    imageProcessor.setSkippedFilesDestinationDirectory(skippedFilesDestinationDirectory);
    isInterrupted = false;
  }

  @Override
  public void run() {
    try {
      while (shouldStop()) {
        File imageFile;
        imageFile = queue.take();
        try {
          imageProcessor.processFile(imageFile);
        } catch (IOException ex) {
          LOGGER.log(Level.SEVERE, "Error while processing file " + imageFile, ex);
        }
        processedImagesCount.incrementAndGet();
      }
    } catch (InterruptedException e) {
      interrupt();
      e.printStackTrace();
    }

  }

  private boolean shouldStop() {
    if (isInterrupted) {
      LOGGER.log(Level.WARNING, "ImageOrganizer is interrupted...exiting");
      return true;
    }
    return false;
  }

  public void interrupt() {
    this.isInterrupted = true;
    LOGGER.log(Level.WARNING, "ImageOrganizer is interrupted");
  }

  public void clearInterrupt() {
    this.isInterrupted = false;
  }
}
